var content = require('../components/content');
var tabs = require('../components/tabs');
var setting = require('../setting');
var chatPeer = require('../chatPeer');
var appEvent = require('../appEvent');
var EventTypes = require('../constants').EventTypes;
var ServiceSwitchStage = require('../constants').ServiceSwitchStage;
var CommandTypes = require('../constants').CommandTypes;
var webapi = require('../api');
var Meta = require('../chatInfo');
var chats = [];
var msgSendInterval = null;
var util = require('../../utils');
module.exports = Chat;

/**
 *
 * @param chatId
 * @param name
 * @param type
 * @param activeType
 * @constructor
 */
function Chat(chatId, name, type, activeType) {
  this.chatId = chatId;
  this.name = name;
  this.type = type;
  tabs.addTab(chatId, name, type);
  chats.push(this);

  getContentInfo(Meta.type, activeType, chatId, function (err, info) {
    if (err) info = {};
    var tabType = activeType || Meta.type;
    this.content = content.create(chatId, type, tabType, info);
    this.chatList = this.content.chatList;
    setting.resize();
    console.log('chats', chats);
    $('body').trigger('set.send.key', $('.set-send-key input[name=sendKey][checked]').val());
    this.isReady = true;
    this.readyCallback && this.readyCallback();
  }.bind(this));
}
Chat.prototype.ready = function (callback) {
  if (this.isReady) {
    return callback();
  }
  this.readyCallback = callback;
};

Chat.prototype.setFromSuid = function (suid) {
  this.fromSuid = suid;
  console.log('set from suid', suid);
};

Chat.prototype.sendMessage = function () {
  if (!this.fromSuid) {
    this.chatList.appendNotice('暂无客服接待，请联系开思客服');
  }
  if (chats[0].isConnected) {
    var chatType = this.type;
    var chatId = this.chatId;
    var fromSuid = this.fromSuid;
    var chatList = this.content.chatList;
    var $input = $('#chat-' + this.chatId).find('.ipt-content');
    var $all = $input.contents();
    if (!$all.length) {
      return;
    }
    var text = '';
    $all.each(function (index, ele) {
      //TextNode 文字节点直接添加到text
      if (ele.nodeType == 3) {
        text += ele.nodeValue + '\n';
        return;
      }

      var $ele = $(ele);

      // 如果子节点有图片，则先发送该节点文字，再发图片
      var $childrenImg = $ele.find('img');
      if ($childrenImg.length) {
        text += $ele.text();
        sendText();
        $childrenImg.each(function (index, img) {
          sendImage(img);
        });
        return;
      }

      // 如果是图片，发送之前的文字，再发图片
      if (ele.tagName == 'IMG') {
        sendText();
        sendImage(ele);
        return;
      }

      // 其它情况取出文字
      text += $ele.text() + '\n';
    });

    // 最后将剩下的文字发送出去
    sendText();
    $input.empty();

    // 将光标移动到最后，解决 edge 浏览器 + 系统自带输入法导致发送一条消息后只能输入字母的BUG
    if (window.getSelection) {
      var sel = window.getSelection();
      var range = document.createRange();
      range.selectNodeContents($input[0]);
      range.collapse(false);
      sel.removeAllRanges();
      sel.addRange(range);
    }
  } else {
    this.chatList.appendNotice('由于您连续10分钟未发布任何消息，系统已经终止了此次咨询。如需继续咨询，' +
      '<a href="javascript:location.reload();">请点击此处</a>');
  }

  //$input.closest('.im-edit-area')
  //  .find('.im-edit-tip').html('还可以输入<span class="still-count">' + (350 - $input.text().length) + '</span>字');

  function sendText() {
    // 发送文本消息
    text = decodeURI(encodeURI(text).replace(/%C2%A0/g, '')).trim();
    if (text) {
      var msg = {
        content: text,
        type: 'text',
        time: new Date().getTime(),
        hasPrefix: false,
        msgId: util.createRandomId()
      };

      if (fromSuid) {
        msg.touid = fromSuid;
        msg.hasPrefix = false;
      }

      chatList.appendMsg(true, msg);
      chatPeer.sendMessage(msg);
      text = '';
    }
  }

  function sendImage(img) {
    var msg = {
      content: img.src,
      type: 'image',
      time: new Date().getTime(),
      hasPrefix: false,
      img: img,
      msgId: util.createRandomId()
    };

    if (chatType == 'chat') {
      msg.touid = chatId;
    }

    if (fromSuid) {
      msg.touid = fromSuid;
      msg.hasPrefix = false;
    }

    chatList.appendMsg(true, msg);
    chatPeer.sendMessage(msg);
  }
};

/**
 * 关闭会话
 */
Chat.prototype.close = function () {
  var id = this.chatId;
  // 倒序，从列表中删除会话
  for (var i = chats.length - 1; i > -1; i--) {
    if (chats[i].chatId == id) {
      chats.splice(i, 1);
    }
  }
  tabs.removeTab(id);
  this.content.remove();
};

/**
 * 激活会话
 */
Chat.prototype.active = function () {
  tabs.activeTab(this.chatId);
  this.content.active();
  //维修厂连接上
  chats[0].isConnected = true;
  //第一个chat激活才设定计时器
  if (chats.length == 1) {
    //设定计时器
    createMsgSendInterval();
  }

  appEvent.addEventListener(EventTypes.SEND_MESSAGE, function (data) {
    chats[0].isConnected = true;
    if (msgSendInterval) {
      clearInterval(msgSendInterval);
      msgSendInterval = null;
    }
    //设定计时器
    createMsgSendInterval();
  });
};

Chat.isChatExists = function (chatId) {
  for (var i = 0; i < chats.length; i++) {
    if (chats[i].chatId == chatId) {
      return true;
    }
  }
  return false;
};

Chat.getChat = function (chatId) {
  for (var i = 0, len = chats.length; i < len; i++) {
    if (chats[i].chatId == chatId) {
      return chats[i];
    }
  }
  return null;
};

Chat.broadCastNotice = function (content, url, type) {
  for (var i = 0; i < chats.length; i++) {
    chats[i].chatList.appendNotice(content, url, type);
  }
};


// 接收到消息
appEvent.addEventListener(EventTypes.RECEIVED_MESSAGE, function (msg) {
  var currentUserId = chatPeer.currentUserId();
  console.log('current user id', currentUserId, msg);
  webapi.getUserInfo(msg.from).then(function (user) {
    if (currentUserId === msg.from) {
      return webapi.getUserInfo(msg.to);
    } else {
      return user;
    }
  }).then(function (user) {
    msg.nickname = user.nickname;

    var chat = Chat.getChat(user.storeId);

    // 只允许当前会话
    if(!chat || user.id !== chat.fromSuid) {
      return;
    }

    if (msg.type === 'command') {
      if (!chat) {
        return;
      }
      var data = msg.content;
      if (data.type === CommandTypes.SWITCH_SERVICE) {
        if (data.stage === ServiceSwitchStage.SERVICE_SWITCH_REQUEST) {
          webapi.getUserInfo(data.toServiceId).then(function (serviceUser) {
            chat.setFromSuid(serviceUser.id);
            chat.chatList.appendNotice('当前会话已经由 <span style="color:#ff211c">' + user.nickname + '</span> 转接至 <span style="color:#ff211c">' + serviceUser.nickname + '</span> 为您服务');
            chat.chatList.appendNotice('<span style="color:#ff211c">' + serviceUser.nickname + '</span> 已经加入会话');
            chatPeer.sendMessage({
              type: 'command',
              content: {
                type: CommandTypes.SWITCH_SERVICE,
                stage: ServiceSwitchStage.SERVICE_SWITCH_RECEIVED,
                fromServiceId: msg.from,
                fromServiceNickname: msg.nickname
              },
              touid: data.toServiceId
            });
          });
        } else if (data.stage === ServiceSwitchStage.SERVICE_SWITCH_RESET) {
          chat.setFromSuid(msg.from);
          chat.chatList.appendNotice('客服已转接至 <span style="color:#ff211c">' + msg.nickname + '</span>');
        }
      }
      return;
    }

    if (!chat) {
      console.log('会话不存在，建立新的会话', user.storeId || user.id);
      chat = new Chat(user.storeId, user.storeName || user.nickname || msg.fromSuid, null, 'store');
      chat.ready(function () {
        chat.active();
        appendMsg(msg);
      });

      if (msg.from === currentUserId) {
        chat.setFromSuid(msg.to);
      } else {
        chat.setFromSuid(msg.from);
      }
      return;
    }

    if (!chat.chatList || !chat.chatList.length) { // 如果当前会话没有消息，则更改客服
      if (msg.from === currentUserId) {
        chat.setFromSuid(msg.to);
      } else {
        chat.setFromSuid(msg.from);
      }
      // 切换客服
      $('#chat-' + user.storeId + ' p:contains(加入会话) span').text(user.nickname);
    }

    appendMsg(msg);

    function appendMsg(msg) {
      if (msg.from == currentUserId) {
        chat.chatList.appendMsg(true, msg);
      } else {
        chat.chatList.appendMsg(false, msg);
      }
    }
  });
});

appEvent.addEventListener(EventTypes.UPDATED_USER_INFO, function (user) {
  console.log('更新用户信息', user);
  webapi.getUserInfo(user.uid, function (err, store) {
    if (err) {
      return;
    }
    // 替换用户名
    $('#chat-' + store.storeId + ' .im-service .message-owner:contains(' + user.uid + ')').html(user.nickname || user.uid);
  });
});

appEvent.addEventListener(EventTypes.OFFLINE, function (data) {
  console.log('OFFLINE:broadcast notice', data);
  Chat.broadCastNotice('您已断开与服务器的连接，<a class="reconnect" href="#">点击重连</a>');
});


function makeUrl(tabType, activeChatId) {
  var url;
  if (tabType == 'store') {
    url = '/ec-api/' + tabType + '/' + (activeChatId || Meta.chatId);
    return url;
  }
  url = '/ec-api/' + tabType + '/' + Meta.clueId;
  return url;
}

function getContentInfo(tabType, activeType, activeChatId, callback) {
  var info = null;
  var data = {userId: Meta.username};
  $.ajax({
    method: 'GET',
    url: makeUrl(activeType || tabType, activeChatId),
    data: data,
    success: function (data) {
      info = data;
      callback(null, info);
    },
    error: function (error) {
      console.log(error);
      callback(error);
    }
  });
}

function createMsgSendInterval() {
  //定时器，超过10min不发送消息断开连接
  msgSendInterval = setInterval(function () {
    chatPeer.disconnect();
    chats[0].isConnected = false;
    chats[0].chatList.appendNotice('由于您连续10分钟未发布任何消息，系统已经终止了此次咨询。如需继续咨询，' +
      '<a href="javascript:location.reload();">请点击此处</a>');
    clearInterval(msgSendInterval);
    msgSendInterval = null;
  }, 10 * 60 * 1000);
}
